package cgd;

import cdp.Objeto;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public abstract class DaoJpa <T extends Objeto> {

    static EntityManagerFactory emf = Persistence.createEntityManagerFactory("pw-webappPU");
    static EntityManager em = emf.createEntityManager();

    public T salvar(T obj) throws Exception {
        try {
            em.getTransaction().begin();
            if (obj.getId() == null) {
                em.persist(obj);
            } else {
                obj = em.merge(obj);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            throw ex;
        }
        return obj;
    }
    
    public void excluir(T obj) throws Exception {
        try {
            em.getTransaction().begin();
            em.remove(obj);
            em.getTransaction().commit();
        } catch (Exception ex) {
            throw ex;
        }
    }
    
    public T consultar(T obj) throws Exception {
        try {
            return (T)em.find(obj.getClass(), obj.getId());
        }
        catch (Exception ex) {
            throw ex;
        }
    }
    
    public List<T> buscar(T obj) throws Exception {
        try {
            Query q = em.createQuery("SELECT t FROM " + obj.getClass().getSimpleName() + " t ");
            return q.getResultList();
        }
        catch (Exception ex) {
            throw ex;
        }
    }  
}
